package com.burst.reptile.modular.system.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.burst.reptile.common.constant.UserConstants;
import com.burst.reptile.common.utils.SecurityUtils;
import com.burst.reptile.common.utils.ToolUtil;
import com.burst.reptile.framework.web.entity.LayuiTreeSelect;
import com.burst.reptile.modular.system.entity.SysMenu;
import com.burst.reptile.modular.system.entity.SysUser;
import com.burst.reptile.modular.system.mapper.SysMenuMapper;
import com.burst.reptile.modular.system.mapper.SysRoleMenuMapper;
import com.burst.reptile.modular.system.service.ISysMenuService;
import com.burst.reptile.modular.system.vo.RouterVo;

import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;

/**
 * <p>
 * 菜单权限表 服务实现类
 * </p>
 *
 * @author wujin
 * @since 2020-05-22
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService {

	private final SysRoleMenuMapper roleMenuMapper;

	@Override
	public Set<String> selectMenuPermsByUserId(Long userId) {
		List<String> perms = this.baseMapper.selectMenuPermsByUserId(userId);
		Set<String> permsSet = new HashSet<>();
		for (String perm : perms) {
			if (StrUtil.isNotEmpty(perm)) {
				permsSet.addAll(Arrays.asList(perm.trim().split(",")));
			}
		}
		return permsSet;
	}

	@Override
	public List<SysMenu> selectMenuTreeByUserId(Long userId) {
		List<SysMenu> menus = null;
		if (SecurityUtils.isAdmin(userId)) {
			menus = this.baseMapper.selectMenuTreeAll();
		} else {
			menus = this.baseMapper.selectMenuTreeByUserId(userId);
		}
		return getChildPerms(menus, 0);
	}

	@Override
	public List<RouterVo> buildMenus(List<SysMenu> menus) {
		List<RouterVo> routers = new LinkedList<RouterVo>();
		for (SysMenu menu : menus) {
			RouterVo router = new RouterVo();
			router.setShow("0".equals(menu.getVisible()));
			router.setName(menu.getMenuName());
			router.setUrl(getRouterPath(menu));
			router.setIcon(menu.getIcon());
			if (menu.getIsFrame() == 0) {
				router.setTarget("_blank");
			} else {
				router.setTarget("_self");
			}
			List<SysMenu> cMenus = menu.getChildren();
			if (!cMenus.isEmpty() && cMenus.size() > 0 && "M".equals(menu.getMenuType())) {
				router.setSubMenus(buildMenus(cMenus));
			}
			routers.add(router);
		}
		return routers;
	}

	/**
	 * 获取路由地址
	 * 
	 * @param menu 菜单信息
	 * @return 路由地址
	 */
	public String getRouterPath(SysMenu menu) {
		String routerPath = menu.getPath();
		return routerPath;
	}

	/**
	 * 根据父节点的ID获取所有子节点
	 * 
	 * @param list     分类表
	 * @param parentId 传入的父节点ID
	 * @return String
	 */
	public List<SysMenu> getChildPerms(List<SysMenu> list, int parentId) {
		List<SysMenu> returnList = new ArrayList<SysMenu>();
		for (Iterator<SysMenu> iterator = list.iterator(); iterator.hasNext();) {
			SysMenu t = (SysMenu) iterator.next();
			// 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
			if (t.getParentId() == parentId) {
				recursionFn(list, t);
				returnList.add(t);
			}
		}
		return returnList;
	}

	/**
	 * 递归列表
	 * 
	 * @param list
	 * @param t
	 */
	private void recursionFn(List<SysMenu> list, SysMenu t) {
		// 得到子节点列表
		List<SysMenu> childList = getChildList(list, t);
		t.setChildren(childList);
		for (SysMenu tChild : childList) {
			if (hasChild(list, tChild)) {
				// 判断是否有子节点
				Iterator<SysMenu> it = childList.iterator();
				while (it.hasNext()) {
					SysMenu n = (SysMenu) it.next();
					recursionFn(list, n);
				}
			}
		}
	}

	/**
	 * 得到子节点列表
	 */
	private List<SysMenu> getChildList(List<SysMenu> list, SysMenu t) {
		List<SysMenu> tlist = new ArrayList<SysMenu>();
		Iterator<SysMenu> it = list.iterator();
		while (it.hasNext()) {
			SysMenu n = (SysMenu) it.next();
			if (n.getParentId().longValue() == t.getMenuId().longValue()) {
				tlist.add(n);
			}
		}
		return tlist;
	}

	/**
	 * 判断是否有子节点
	 */
	private boolean hasChild(List<SysMenu> list, SysMenu t) {
		return getChildList(list, t).size() > 0 ? true : false;
	}

	@Override
	public List<SysMenu> selectMenuList(SysMenu menu, Long userId) {
		List<SysMenu> menuList = null;
		// 管理员显示所有菜单信息
		if (SysUser.isAdmin(userId)) {
			menuList = this.baseMapper.selectMenuList(menu);
		} else {
			menu.getParams().put("userId", userId);
			menuList = this.baseMapper.selectMenuListByUserId(menu);
		}
		return menuList;
	}

	@Override
	public String checkMenuNameUnique(SysMenu menu) {
		Long menuId = ToolUtil.isEmpty(menu.getMenuId()) ? -1L : menu.getMenuId();
		SysMenu info = this.baseMapper.selectOne(
				new QueryWrapper<SysMenu>().eq("menu_name", menu.getMenuName()).eq("parent_id", menu.getParentId()));
		if (ToolUtil.isNotEmpty(info) && info.getMenuId().longValue() != menuId.longValue()) {
			return UserConstants.NOT_UNIQUE;
		}
		return UserConstants.UNIQUE;
	}

	@Override
	public int insertMenu(SysMenu menu) {
		return this.baseMapper.insert(menu);
	}

	@Override
	public int updateMenu(SysMenu menu) {
		return this.baseMapper.updateById(menu);
	}

	@Override
	public boolean hasChildByMenuId(Long menuId) {
		int result = this.baseMapper.selectCount(new QueryWrapper<SysMenu>().eq("parent_id", menuId));
		return result > 0 ? true : false;
	}

	@Override
	public boolean checkMenuExistRole(Long menuId) {
		int result = roleMenuMapper.checkMenuExistRole(menuId);
		return result > 0 ? true : false;
	}

	@Override
	public int deleteMenuById(Long menuId) {
		return this.baseMapper.deleteById(menuId);
	}

	@Override
	public List<LayuiTreeSelect> buildMenuTreeSelect(List<SysMenu> menus) {
		List<SysMenu> menuTrees = buildMenuTree(menus);
		return menuTrees.stream().map(LayuiTreeSelect::new).collect(Collectors.toList());
	}

	@Override
	public List<SysMenu> buildMenuTree(List<SysMenu> menus) {
		List<SysMenu> returnList = new ArrayList<SysMenu>();
		for (Iterator<SysMenu> iterator = menus.iterator(); iterator.hasNext();) {
			SysMenu t = (SysMenu) iterator.next();
			// 根据传入的某个父节点ID,遍历该父节点的所有子节点
			if (t.getParentId() == 0) {
				recursionFn(menus, t);
				returnList.add(t);
			}
		}
		if (returnList.isEmpty()) {
			returnList = menus;
		}
		return returnList;
	}

	@Override
	public List<Long> selectMenuListByRoleId(Long roleId) {
		return this.baseMapper.selectMenuListByRoleId(roleId);
	}

}
